 package com.gamehouse.eggpoacher;

import java.util.ArrayList;


import java.util.Random;

import org.w3c.dom.Text;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import Models.*;

public class menuPlay extends Activity{
	
	ProgressBar myProgressBar;
    AlertDialog.Builder alertbox;
    AlertDialog.Builder alertBoxInput;
	GridView gridview ;
	ImageAdapter imageAdapter;//classe que cria gridiview
	ArrayList<ImageView> imageList;//guarda imageviews
	Thread timerNivel;//thread deste nivel
	Level level = new Level(this);
	
	MediaPlayer mpPop;
	
	Toast toast;
	TextView scoreText;	
	Vibrator v;
	Drawable d;
	//variaveis que vao ser usadas para verificar se passa de nivel
	int passaNivel ;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
            WindowManager.LayoutParams.FLAG_FULLSCREEN );
			setContentView(R.layout.play);
			
			
			level.getCurrentGame(this);
			level.getLevelProperties(this);
			level.getEggProperties(this);
			v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            Resources res = getResources();

        mpPop = MediaPlayer.create(this, R.raw.popsound);
		myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
		myProgressBar.setMax(level.getEggNumber());
		myProgressBar.setProgressDrawable(res.getDrawable(R.drawable.myprogressbar));
		scoreText = (TextView) findViewById(R.id.textViewDisplayScore);	
		scoreText.setText(Integer.toString(level.getLastLevelScore()));
				
        gridview = (GridView) findViewById(R.id.play_gridview);
		imageAdapter = new ImageAdapter(this);
		gridview.setAdapter(imageAdapter);   

		timerNivel = new Thread(myThread);
		timerNivel.start();
	
		alertbox = new AlertDialog.Builder(this);
	    alertbox.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
	    	public void onClick(DialogInterface arg0, int arg1) {
	    		if(passaNivel == 0)
	    		{
	    			restartActivity();   
	    		}else if (passaNivel == 1)
	    		{
	    			//new alert box with input name
	    			alertBoxInput.show();	
	    		}else 
	    		{
	    			alertBoxInput.show();
	    		}
	    	}
	    });
	    
	    alertBoxInput = new AlertDialog.Builder(this);
	    alertBoxInput.setTitle("Submit Score");  
	    alertBoxInput.setMessage("Enter your Name :");                
        // Set an EditText view to get user input   
	    final EditText input = new EditText(this); 
        alertBoxInput.setView(input);
        alertBoxInput.setPositiveButton("Ok", new DialogInterface.OnClickListener() {  
	        public void onClick(DialogInterface dialog, int whichButton) {  
	            String value = input.getText().toString();
	            //save score in database
	            level.insertScore(value);
	            finishActivity();
	            return;                  
	           }  
	         });  
	     alertBoxInput.setNegativeButton("Submit Online", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int which) {
	            	finishActivity();
	                return;   
	            }
	        });
	    
	    //toast properties 
	    Context context = getApplicationContext();
		CharSequence text = "Level " + level.getLevelNumber() + "...Get Ready!!";
		int duration = Toast.LENGTH_LONG;
		toast = Toast.makeText(context, text, duration);
	
	}//onCreate close
	
	// Volta para activity principal
	public void mostrarMenu(View view){
		android.os.Process.killProcess(android.os.Process.myPid());		
	}
	
	//back button para voltar a actividade anterior e matar a activity actual
	@Override
	public void onBackPressed() {
	    // do something on back.
		android.os.Process.killProcess(android.os.Process.myPid());
	    return;
	}
	
	//mostra imagem numa posiçao aleatoria
	public void mostrarImagem(){	
		Random aRandom = new Random();
		 
	     int randomNumber = aRandom.nextInt(12);
	     imageList = imageAdapter.getImageList(); 
	     if(imageList.get(randomNumber).getVisibility() == View.INVISIBLE)
	     {
	    	Egg egg = new Egg(imageList.get(randomNumber),scoreText,v, level.getRandomEgg(), this, mpPop);
		    egg = null;		    
	     }	     
	}
		
	//thread que controla o timer do nivel
	private Runnable myThread = new Runnable(){		
		public void run() {
			while (level.getEggNumber() != 0){
				try{
					if(level.getEggNumber() == level.getInicialEggNumber())
					{
						toast.show();
						Thread.sleep(1000);//tempo que demora a aparecer um novo ovo
						myHandle.sendMessage(myHandle.obtainMessage());
						Thread.sleep(1000);//tempo que demora a aparecer um novo ovo
					}
					else
					{
						myHandle.sendMessage(myHandle.obtainMessage());
						Thread.sleep((long) level.getTimer());//tempo que demora a aparecer um novo ovo
					}				
				}
				catch(Throwable t){
				}
			}			
			myHandle2.sendMessage(myHandle2.obtainMessage()); //acaba o nivel
		}
		
		//handler que mostras imagem e decrementa progress bar
		Handler myHandle = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				if(level.getEggNumber() == 0){					                 
				}else{
					level.setEggNumber(level.getEggNumber() -1);
					mostrarImagem();
					myProgressBar.setProgress(level.getEggNumber());
				}
			}
		};
			
		//handler que acaba o nivel a mostra alert box
		Handler myHandle2 = new Handler(){
			@Override
			public void handleMessage(Message msg) {
					//verifica se fez pontos suficientes
				int myScore = level.getFinalScoreLevel();
			    passaNivel = level.passaNivel(myScore);
			    if ( passaNivel == 0)
			    {
			    	alertbox.setMessage("Level completed!");
			    	alertbox.show();
			    	timerNivel = null;	
			    }else if(passaNivel == 1)
			    {
			    	alertbox.setMessage("Game Over!");
			    	alertbox.show();
			    	timerNivel = null;				    				  				    	
			    }else				    
			    {
			    	alertbox.setMessage("Congratulations! You Won!");
			    	alertbox.show();
			    	timerNivel = null;	
			    }								
			}
		};
			
		};
	
		//comeca um novo nivel
		public void restartActivity(){	
	        Intent intent=new Intent();
	        intent.setClass(this, this.getClass());	        
	        this.finish();
	        this.startActivity(intent);	        	      
	     }
		
		//volta para menu
		public void finishActivity(){	
	        Intent intent=new Intent();
	        intent.setClass(this, this.getClass());	        
	        this.finish();
	     }
}


